import express from 'express';
import ResMsg from '../common/ResMsg';
import data from '../data';
const productRoute = express.Router();

// 猜你喜欢
productRoute.post('/guess', (req, res, next) => {
    const resMsg = new ResMsg(true);
    resMsg.productList = data.products;
    res.json(resMsg);
});

// 商品分类
productRoute.post('/categories', (req, res, next) => {
    const resMsg = new ResMsg(true);
    resMsg.categories = data.categories;
    res.json(resMsg);
});

// 通过商品分类id获取商品列表
productRoute.post('/category/list', (req, res, next) => {
    req.on('data', r => {
        let params = JSON.parse(decodeURIComponent(r));
        let categoryProducts = [];
        for (let item of data.products) {
            if (item.categoryId === params.categoryId) {
                categoryProducts.push(item);
            }
        }
        const resMsg = new ResMsg(true);
        resMsg.categoryProducts = categoryProducts;
        res.json(resMsg);
    });
});

// 商品详情
productRoute.post('/', (req, res, next) => {
    req.on('data', r => {
        let params = JSON.parse(decodeURIComponent(r));
        let resMsg = new ResMsg(false);
        resMsg.msg = '查询失败，无此商品';
        for (const item of data.products) {
            if (params.productId === item.id) {
                resMsg = new ResMsg(true);
                resMsg.productDetail = item;
                break;
            }
        }
        res.json(resMsg);
    });
});

export default productRoute;